<?php


class dbTool
{
    private static function getDataBaseType(): string
    {
        return json_decode(file_get_contents(CONFIG_PATH . "db_config.json"), true)['type'];
    }

    private static function connectDB(): mysqli
    {
        $a = json_decode(file_get_contents(CONFIG_PATH . "db_config.json"), true);
        return mysqli_connect($a['host'], $a['user'], $a['pwd'], $a['name'], $a['port']);
    }

    private static function getTableHead(array $tableData): array
    {
        $b = array();
        for ($i = 0; $i < count($tableData[0]); $i++) {
            $b[$tableData[0][$i]] = $i;
        }
        return $b;
    }

    public static function createTable(string $tableName, array $cols): array
    {
        $result = "";
        switch (self::getDataBaseType()) {
            case "file":
                file_put_contents(FILE_DB_PATH . $tableName . ".xcdb", stringTool::encode(json_encode([0 => $cols]), XCGZS_SECRET, true));
                $result = ["status" => "success"];
                break;
            case "mysql":
                $a = "CREATE TABLE IF NOT EXISTS `$tableName` (`id` int NOT NULL AUTO_INCREMENT,";
                foreach ($cols as $value) {
                    $a .= '`' . $value . '` longtext NOT NULL,';
                }
                $a .= "PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
                $conn = self::connectDB();
                if (!mysqli_query($conn, $a)) $result = ["status" => "fail", "reason" => mysqli_error($conn)]; else $result = ["status" => "success"];
                break;
        }
        return $result;
    }

    public static function insert(string $tableName, array $keys, array $values): array
    {
        $result = "";
        switch (self::getDataBaseType()) {
            case "file":
                $a = json_decode(stringTool::decode(file_get_contents(FILE_DB_PATH . $tableName . ".xcdb"), XCGZS_SECRET, true), true);
                // 原数据
                $b = array();
                // 表头数据
                for ($i = 0; $i < count($a[0]); $i++) {
                    $b[$a[0][$i]] = $i;
                }
                $c = array();
                //临时数据，用于插入
                for ($i = 0; $i < count($values); $i++) {
                    $c[$b[$keys[$i]]] = $values[$i];
                }
//                $a['data'][++$a['counter']] = $c;
                $a[count($a)] = $c;
                file_put_contents(FILE_DB_PATH . $tableName . ".xcdb", stringTool::encode(json_encode($a), XCGZS_SECRET, true));
                $result = ["status" => "success"];
                break;
            case "mysql":
                $a = "INSERT INTO `$tableName` (";
                foreach ($keys as $key) {
                    $a .= "`" . $key . "`,";
                }
                $a = substr($a, 0, strlen($a) - 1);
                $a .= ") VALUES (";
                foreach ($values as $value) {
                    $a .= "'" . $value . "',";
                }
                $a = substr($a, 0, strlen($a) - 1);
                $a .= ");";
                $conn = self::connectDB();
                if (!mysqli_query($conn, $a)) $result = ["status" => "fail", "reason" => mysqli_error($conn)]; else $result = ["status" => "success"];
                break;
        }
        return $result;
    }

    public static function select(string $tableName, array $keys, array $where): array
    {
        $result = "";
        switch (self::getDataBaseType()) {
            case "file":
                $a = json_decode(stringTool::decode(file_get_contents(FILE_DB_PATH . $tableName . ".xcdb"), XCGZS_SECRET, true), true);
                $data = array();
                $b = self::getTableHead($a);
                foreach ($a as $value) {
                    if ($value[$b[array_keys($where)[0]]] == $where[array_keys($where)[0]]) {
                        $t = array();
                        foreach ($b as $item) {
                            if ($keys[0] == "*" || in_array($item, $keys)) {
                                $t[array_keys($b)[$item]] = $value[$item];
                            }
                        }
                        $data[count($data)] = $t;
                    }
                }
                $data = arrayTool::removeFirst($data);
                $result = ["status" => "success", "data" => $data];
                break;
            case "mysql":
                $k = "";
                if ($keys[0] == "*") {
                    $k = $keys[0];
                } else {
                    foreach ($keys as $item) {
                        $k .= $item . ",";
                    }
                    $k = substr($k, 0, strlen($k) - 1);
                }
                $w = "";
                if (count($where)) {
                    $w = "WHERE ";
                    for ($i = 0; $i < count($where); $i++) {
                        $w .= array_keys($where)[$i] . "='" . $where[array_keys($where)[$i]] . "',";
                    }
                    $w = substr($w, 0, strlen($w) - 1);
                }
                $a = "SELECT $k FROM $tableName $w;";
                $conn = self::connectDB();
                $r = mysqli_query($conn, $a);
                if (!$r) {
                    $result = ["status" => "fail", "reason" => mysqli_error($conn)];
                }
                $data = array();
                while ($row = mysqli_fetch_assoc($r)) {
                    unset($row['id']);
                    $data[count($data)] = $row;
                }
                $result = ["status" => "success", "data" => $data];
                break;
        }
        return $result;
    }

    public static function deleteRow(string $tableName,array $where)
    {
        $result = "";
        switch (self::getDataBaseType()){
            case "file":
                if (!count($where)){
                    $result=["status"=>"fail","reason"=>"where参数不能为空数组，若要删除所有数据请指定where为[*]"];
                    break;
                }
                $a = json_decode(stringTool::decode(file_get_contents(FILE_DB_PATH . $tableName . ".xcdb"),XCGZS_SECRET,true),true);
                $h = self::getTableHead($a);
                $c = array();
                for ($i = 1;$i < count($a);$i++){//遍历总数据的每一行
                    for ($j = 0;$j < count($where);$j++){//遍历条件的数据
                        if ($a[$i][$h[array_keys($where)[$j]]] == $where[array_keys($where)[$j]]){
                            $c[count($c)]=$a[$i];
                        }
                    }
                }
                foreach ($c as $item) {
                    while (in_array($item,$a)){
                        $a = arrayTool::remove($a,$item);
                    }
                }
                file_put_contents(FILE_DB_PATH . $tableName . ".xcdb",stringTool::encode(json_encode($a),XCGZS_SECRET,true));
                $result=["status"=>"success"];
                break;
            case "mysql":
                $a = "DELETE FROM $tableName";
                $c = self::connectDB();
                if (count($where)){
                    $a .= " WHERE ";
                    for ($i = 0;$i < count($where);$i++){
                        $a.=array_keys($where)[$i]."='".$where[array_keys($where)[$i]]."',";
                    }
                    $a = substr($a,0,strlen($a)-1);
                }
                if (mysqli_query($c,$a)){
                    $result = ["status"=>"success"];
                }else{
                    $result = ["status"=>"fail","reason"=>mysqli_error($c)];
                }
                break;
        }
        return $result;
    }

    public static function deleteTable(string $tableName): array
    {
        $result = [];
        switch (self::getDataBaseType()) {
            case "file":
                if (file_exists(FILE_DB_PATH . $tableName . ".xcdb")) {
                    if (unlink(FILE_DB_PATH . $tableName . ".xcdb")) {
                        $result = ["status" => "success"];
                    } else {
                        $result = ["status" => "fail", "reason" => ""];
                    }
                }else {
                    $result = ["status" => "fail","reason"=>"表格不存在"];
                }
                break;
            case "mysql":
                $a = "DROP TABLE $tableName";
                $conn = self::connectDB();
                $r = mysqli_query($conn, $a);
                if (!$r) {
                    $result = ["status" => "fail", "reason" => mysqli_error($conn)];
                    return $result;
                }
                $result = ["status" => "success"];
                break;
        }
        return $result;
    }
}